package com.itheima.testjob;

import com.itheima.constant.RedisConst;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Set;

@RestController
public class ClearImgJob {
	@Autowired
	JedisPool jedisPool;

	public void  run(){
		Set<String> imgNames = jedisPool.getResource().smembers(RedisConst.SETMEAL_PIC_RESOURCES);

		Calendar cal = Calendar.getInstance();
		//获取昨天日期
		cal.add(Calendar.DAY_OF_MONTH,-1);

		Date date = cal.getTime();//昨天日期

		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		//昨天图片的前6位
		String dateStr = simpleDateFormat.format(date);

		for (String imgName:imgNames
			 ) {

			if(imgName !=null && imgName.startsWith(dateStr)){

				//删除千牛云上的图片
				delQiniu(imgName);
				//删除redis中图片名称
				jedisPool.getResource().srem(RedisConst.SETMEAL_PIC_RESOURCES,imgName);

			}

		}

	}


	public void delQiniu(String imgName){

		//构造一个带指定Zone对象的配置类
		Configuration cfg = new Configuration(Zone.zone0());
		String ak = "QpB4fUbPObhd0b0kI8QYtV9xAMkOaFJVN-Sd_yna";
		String sk = "VUhInOK9SLahdSRbVqpEb851_vJnDeVWHVSszQky";
		String key = imgName;
		Auth auth = Auth.create(ak, sk);
		BucketManager bucketManager = new BucketManager(auth, cfg);
		try {
			bucketManager.delete("itcasthealth359", key);
		} catch (QiniuException ex) {
			//如果遇到异常，说明删除失败
			System.err.println(ex.code());
			System.err.println(ex.response.toString());
		}



	}
}
